import * as path from 'path';

import { parseArgs } from '../../environment/node/argv';
import { assign } from 'egret/base/common/objects';
import { IWindowConfiguration } from '../common/window';
import { WebPreferences } from 'electron';
import { BrowserWindowEx } from './browserWindowEx';
import { IEnvironmentService } from 'egret/platform/environment/common/environment';
import { IInstantiationService } from 'egret/platform/instantiation/common/instantiation';
import { session } from 'electron';

export class GameWindow extends BrowserWindowEx {
	/**
	 *
	 */
	constructor(windowId: string,
		newWindow: boolean,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IEnvironmentService environmentService: IEnvironmentService) {
		super(windowId, newWindow, environmentService);
	}

	protected initWindow(newWindow: boolean): void {
		super.initWindow(newWindow);
		this._win.setTitle('Game');
		this._win.removeMenu();
	}

	protected getWebPreferences(): WebPreferences {
		if (this.environmentService.args.gamefree) { // 项目debug 保存异步写文件支持;
			process.env.GAME_FREE = "1";
			const def = super.getWebPreferences();
			def.session = session.defaultSession;
			def.preload = path.join(__dirname, 'game_preload.js');
			return def;
		}
		return {
			webSecurity: true,
			contextIsolation: true,
			nodeIntegration: false,
			session: session.defaultSession,
			preload: path.join(__dirname, 'game_preload.js')
		};
	}

	protected getUrl(windowConfiguration: IWindowConfiguration): string {
		windowConfiguration.windowId = this._win.id;
		const environment = parseArgs(process.argv);
		const config = assign(environment, windowConfiguration);
		const param = windowConfiguration.param ? `&${windowConfiguration.param}` : "";
		return `file://${path.join(windowConfiguration.folderPath, './index.html')}?config=${encodeURIComponent(JSON.stringify(config))}${param}`;
	}

	public load(config: IWindowConfiguration): void {
		// 项目debug模式 document 初始化时为一个新的空白对象;
		session.defaultSession.loadExtension(path.join(__dirname, "../plugins/egret_inspector"), { allowFileAccess: true }).then(ext => {
			console.log("load extension suc ", ext);
		}).catch(err => {
			console.error("load extension err " + err);
		}).finally(() => {
			super.load(config);
		});
	}
}
